// JavaScript Document
var mouse_is_inside = false;
var NSFrmReveal = false;

var flyout = false;

//Function for ajax updates
function ajax_realTime() {
	ajax();
	notifications();				//Almost realtime notification updates
	scroll();
}	

 
function notifications(){
	var data;
	$.getJSON( "proc/ajax-flyout.php", data, function (json){
		if(json.status){
			if(json.alert){
				$('.not-top .alert-icon').show();
			}
			if(json.newmsg){
				$('.msg-top .alert-icon').show();
			}
		}
	});
	
	setTimeout("notifications()",1000*15);
}

function loadAlerts(){
	$.ajax({
		type: "POST",
		url: "proc/ajaxNotification.php",
		cache: false,
		success: function(data){
			if(data != ''){
				$('#notificationWrap').html(data);
			}
		}
	});
	
}

function loadMessages(){
	$.ajax({
		type: "POST",
		url: "proc/ajax-messages.php",
		cache: false,
		success: function(data){
			if(data != ''){
				$('#msg-wrap').html(data);
			}
		}
	});
	
}


function scroll(){
	var objDiv = document.getElementById("updates");
	objDiv.scrollTop = objDiv.scrollHeight;
}
    
function ajax() {
	var dataString = '';
	var storyid = $('#ntwists').data('id');
	var dataString = 'storyid=' + storyid;
	var tHeight = $('#twists').height();
	
	$.ajax({
		type: "POST",
		url: "proc/ajax.php",
		dataType: 'json',
		data: dataString,
		cache: false,
		success: function(data){
			if(data.hasOwnProperty('storyLine')) {
				$("ul#updates li:last").before(data.storyLine);
				$("ul#updates li:last").prev().fadeIn("slow");
				$("#elPaneWrap").fadeOut();
				$("#ntwists").empty();
				scroll();
			} //if(data.storyLine != '')

			if(data.hasOwnProperty('entryLine') && data.entryLine != null) {
				$("#elPaneWrap").fadeIn();
				$('#twists').css({ 'min-height' : tHeight });
				$("#ntwists").empty();
				$("#twists").show();
				$("#blankTwists").hide();
				$("ul#ntwists").append(data.entryLine);
				$("ul#entry:first").fadeIn("slow");
			} //if(data.entryLine != '')						
		} // Success
	});
	setTimeout("ajax()",1000*10);
}

$(function() { 

	//Get invite pop up
	$('#getInvite').live('click', function(){
		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
		$('#modalCon').load('inc/getInvite.php');
	});
	
	// Request Invite
	$("#inBtn").live('click', function(){
		$("#invite-error").hide('blind', { direction: 'vertical' }, 300);
		$("#in-msg").hide();
		$('#in-loading').show();	
		var email = $("#inviteEmail").val();
		
		if(email == ""){
			$("#invite-error").show('blind', { direction: 'vertical' }, 300);
			$("#invite-null").show();
			$('#in-loading').hide();
		} else {		
			 var dataString = 'email=' + email;
			$.ajax({
				type: "POST",
				url: "proc/reqInvite.php",
				data: dataString,
				dataType: 'json',
				cache: false,
				success: function(data){
					$('#in-loading').hide();		
					if (data.type == 'invalid'){
						$("#invite-error").show('blind', { direction: 'vertical' }, 300);
						$("#invite-invalid").show();
					} else if (data.type == 'exist') {
						$("#invite-error").show('blind', { direction: 'vertical' }, 300);
						$("#invite-exist").show();
					} else if (data.type == 'success') {
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
						$('#modalCon').html("<div class='pMsg'><p>Thank you for requesting an invite. We'll send you your invite as soon as we can support more number of users.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					} else if (data.type == 'error') {
						$("#invite-error").show('blind', { direction: 'vertical' }, 300);
						$("#invite-e").show();
					} 		
				}
			});
		}
	});
	
	//Show user menu or Login form
	$('.show').live('click', function(){
		var id = $(this).attr('id');							//Get the id of the element Clicked
		if(id == 'showSettings'){								//If the element clicked is #showSettings
			$('.showWrap').show();							//Display Settings
		} else if(id == 'showLogin'){								//If the element clicked is #showSettings
			$('.showWrap').show();							//Display Settings
		}
		$(this).removeClass('settingsClick');	//Set Background Color
		$(this).addClass('settingsClicked');
	});
	
	//Disable hide on clicking on the menu element
	$('.showWrap').hover(function(){  mouse_is_inside=true; }, function(){ mouse_is_inside=false; });
	
	//Show flyout
	$('.updates').live('click', function(){
		$(this).siblings('.flyout').show();	//Show flyout
		$(this).addClass('updatesClicked');	//Style click element
		
		$(this).children('.alert-icon').hide();	//Hide alert icon
		var type = $(this).data('type');
		
		if(type == 'alert'){
			loadAlerts();
		} else if (type == 'message'){
			loadMessages();
		}
	});
	
	//Disable hide on clicking the flyout leaflet
	$('.flyout').hover(function(){  flyout=true; }, function(){ flyout=false; });

	//On clicking to any area other than the menu div, hide the div
    $("body").mouseup(function(){ 
        if(!mouse_is_inside) {
			$('.showWrap').hide();
			$('#loginLoading').hide();
			$('#user-email .lError').hide();
			$('#user-email input').val('');
			
			$('.show').removeClass('settingsClicked');
			$('.show').addClass('settingsClick');
		}
		if(!flyout) {
			$('.flyout').hide();
			if($('.updates').hasClass('updatesClicked')){
				$('.updates').removeClass('updatesClicked');
			}
		}
    });
	
	// Reveal Post New Story text area
	$('#sTitle').live('focus', function(){
		if(!NSFrmReveal){
			$("#hideNSFrm").fadeIn(300);
			$("#hideSFrm").show('blind', { direction: 'vertical' }, 300, function(){ NSFrmReveal = true; });
		}
	});
	$('#hideNSFrm').live('click', function(){
		$("#hideNSFrm").fadeOut(300);
		$("#hideSFrm").hide('blind', { direction: 'vertical' }, 300, function(){ NSFrmReveal = false; });
	});
	
	//Modal pop up
	$('.modalClose').live('click', function(){ $('#overlay').fadeOut(300); $('#modalWrap').fadeOut(300); });

	//Show My Stories 
	$('.msNav').live('click', function(){
		var id = $(this).attr('id');							//Get the id of the element Clicked
		$('.msWrap').hide();									//Hide the other tab content
		if(id == 'msAll'){	
			$('#msAllWrap').show();								//Display My Stories: All
			$("#pagetp1").val('all');
			var max = $('#maxallpro').val();
			if(max > 1){
				$('#nextbtn').removeClass();
				$('#nextbtn').addClass('btnB');
				$('#previousbtn').removeClass();
				$('#previousbtn').addClass('btnGrey');
			} else {
				$('#nextbtn').removeClass();
				$('#nextbtn').addClass('btnGrey');
				$('#previousbtn').removeClass();
				$('#previousbtn').addClass('btnGrey');
			}
		} else if(id == 'msOwn'){
			$('#msMyWrap').show();								//Display My Stories: Own
			$("#pagetp1").val('specific');
			var max = $('#maxspecific').val();
			if(max > 1) {
				$('#nextbtn').removeClass();
				$('#nextbtn').addClass('btnB');
				$('#previousbtn').removeClass();
				$('#previousbtn').addClass('btnGrey');
			} else {
				$('#nextbtn').removeClass();
				$('#nextbtn').addClass('btnGrey');
				$('#previousbtn').removeClass();
				$('#previousbtn').addClass('btnGrey');
			}
		} else if(id == 'msFwing'){
			$('#msFwingWrap').show();							//Display My Stories: Own
		} else if(id == 'msFwer'){
			$('#msFwerWrap').show();							//Display My Stories: Own
		}
		$('.msNav').removeClass('msCurrent');					//Set Background Color of the menu
		$(this).addClass('msCurrent');
	});
	
	//Search when magnifying glass is clicked
	$('#search-form .glass').live('click', function() {		
		var name = $("#searchQuery").val();
		if(!(name == "" || name == "Search")){
			var dataPass = 'name='+name;
				$.ajax({
					type: "POST",
					url: "proc/searchstory.php",
					data: dataPass,
					cache: false,
					success: function(html){ $("#rightCol").html(html); }
				});
		}
	});
	//Search When pressed enter key
	$("#searchQuery").keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
  		if ( code == 13 ) { $('#search-form .glass').click(); }
	});
	
	$("#searchQuery").focus(function() { $("#search-query").css({ 'background-color' : '#CCC', 'color' : '#333' }); });
	$("#searchQuery").blur(function() { $("#search-query").css({ 'background-color' : '#727A85', 'color' : '#CCC' }); });
	
	
	//Search MESSAGE magnifying glass is clicked
	$('#msg-search-wrap .glass').live('click', function() {
		var name = $("#msg-search-btn").val();
		if(!(name == "")){
			var dataPass = 'string='+name;
				$.ajax({
					type: "POST",
					url: "proc/searchmessage.php",
					data: dataPass,
					cache: false,
					success: function(html){ 
						$(".msg-list").css({
							"background-color": "#FFF",
							"padding": 0
						});
						$(".msg-list").html(html);
					}
				});
		}
	});
	//Search MESSAGE pressed enter key
	$("#msg-search-btn").keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
  		if ( code == 13 ) { $('#msg-search-wrap .glass').click(); }
	});
	
	
	
	//Next button on home.php
	$('#next').live('click', function(){
		$('.loadingHolder').show();
		var pagetype = window.location.href;
		var pagecal = '';
		pagetype = pagetype.split("#");
		var pagetp = $("#pagetp").val();
		
		if(pagetp == 'freshStories') { pagecal = "proc/freshStories.php";
			var max = $('#maxlatest').val();
		} else { pagecal = "proc/hotStories.php";
			var max = $('#maxhot').val();
		}
		var pageNum = $('#pagenumber').val();
		pageNum++;
		var dataString = "page="+pageNum;	

		$.ajax({
			type: "POST",
			url: pagecal,
			data: dataString,
			cache: false,
			success: function(data){
				$('.loadingHolder').hide();
				if(data != "<div id='content'></div>"){
					$('#content').html(data);
					$('#pagenumber').val(pageNum);
					if(pageNum > 1) {
						$('#previous').removeClass();
						$('#previous').addClass('btnB');
						$('#previous').attr("disabled", false);
					} else {
						$('#previous').removeClass();
						$('#previous').addClass('btnGrey');
						$('#previous').attr("disabled", true);
					}
					if(max <= pageNum) {
						$('#next').removeClass();
						$('#next').addClass('btnGrey');
						$('#next').attr("disabled", true);
					} else {
						$('#next').removeClass();
						$('#next').addClass('btnB');
						$('#next').attr("disabled", false);
					}
				}
			} // Success
		}); //$.ajax({ 
	});	

	//Previous button on home.php
	$('#previous').live('click', function(){
		$('.loadingHolder').show();
		var pagetype = window.location.href;
		var pagecal = '';
		pagetype = pagetype.split("#");
		var pagetp = $("#pagetp").val();
		
		if(pagetp == 'freshStories') { pagecal = "proc/freshStories.php";
			var pagetp = $("#pagetp").val();
		} else { pagecal = "proc/hotStories.php";
			var max = $('#maxhot').val();
		}
		var pageNum = $('#pagenumber').val();

		if(pageNum > 1) {
			pageNum--;
			var dataString = "page="+pageNum;
			$.ajax({
				type: "POST",
				url: pagecal,
				data: dataString,
				cache: false,
				success: function(data){
					$('.loadingHolder').hide();
					$('#content').html(data);
					$('#pagenumber').val(pageNum);
					if(pageNum==1) {
						$('#previous').removeClass();
						$('#previous').addClass('btnGrey');
						$('#previous').attr("disabled", true);
					} else {
						$('#previous').removeClass();
						$('#previous').addClass('btnB');
						$('#previous').attr("disabled", false);
					}
					
					if(max <= pageNum) {
						$('#next').removeClass();
						$('#next').addClass('btnGrey');
						$('#next').attr("disabled", true);
					} else {
						$('#next').removeClass();
						$('#next').addClass('btnB');
						$('#next').attr("disabled", false);
					}
				} // Success
			}); //$.ajax({
		} else {
			$('.loadingHolder').hide();
		}
	});	
	
	//Profile page Next/Prev btns
	$('#nextbtn').live('click', function(){
		var pagecal = '';
		var condiv = '';
		var userpro = $("#upro").val();
		var pagetp = $("#pagetp1").val();
		if(pagetp == 'specific')
		{
			pagecal = "proc/userspecificstory.php";
			condiv = "#msMyWrap";
			var max = $('#maxspecific').val();
		}
		else{
			pagecal = "proc/userallstory.php";
			condiv = "#msAllWrap";
			var max = $('#maxallpro').val();
		}
		var frenId = $('#pagenumber1').val();
		frenId++;
		var dataString = "page="+frenId+"&id="+userpro;
		
		$.ajax({
			type: "POST",
			url: pagecal,
			data: dataString,
			cache: false,
			success: function(data){
				if(data != '<ul><li><span class="pro-notification">No stories to display</span></li></ul>'){
				$(condiv).empty();
				$(condiv).append(data);
				$('#pagenumber1').val(frenId);
				if(frenId > 1)
				{
					$('#previousbtn').removeClass();
					$('#previousbtn').addClass('btnB');
					$('#previousbtn').attr("disabled", false);
				}
				else{
					$('#previousbtn').removeClass();
					$('#previousbtn').addClass('btnGrey');
					$('#previousbtn').attr("disabled", true);
				}
				if(max <= frenId)
				{
					$('#nextbtn').removeClass();
					$('#nextbtn').addClass('btnGrey');
					$('#nextbtn').attr("disabled", true);
				}
				else{
					$('#nextbtn').removeClass();
					$('#nextbtn').addClass('btnB');
					$('#nextbtn').attr("disabled", false);
				}
				
				}
			} // Success
		}); //$.ajax({ 
	});	
	
	$('#previousbtn').live('click', function(){
			var pagecal = '';
			var condiv = '';
			var pagetp = $("#pagetp1").val();
			var userpro = $("#upro").val();
			if(pagetp == 'specific')
			{
				pagecal = "proc/userspecificstory.php";
				condiv = "#msMyWrap";
				var max = $('#maxspecific').val();
			}
			else{
				pagecal = "proc/userallstory.php";
				condiv = "#msAllWrap";
				var max = $('#maxallpro').val();
			}
			var frenId = $('#pagenumber1').val();
			if(frenId > 1)
			{
				frenId--;
			var dataString = "page="+frenId+"&id="+userpro;
			
			$.ajax({
				type: "POST",
				url: pagecal,
				data: dataString,
				cache: false,
				success: function(data){
					if(frenId==1)
					{
						$('#previousbtn').removeClass();
						$('#previousbtn').addClass('btnGrey');
						$('#previousbtn').attr("disabled", true);
					}
					else{
						$('#previousbtn').removeClass();
						$('#previousbtn').addClass('btnB');
						$('#previousbtn').attr("disabled", false);
					}
					
					if(max <= frenId)
					{
						$('#nextbtn').removeClass();
						$('#nextbtn').addClass('btnGrey');
						$('#nextbtn').attr("disabled", true);
					}
					else{
						$('#nextbtn').removeClass();
						$('#nextbtn').addClass('btnB');
						$('#nextbtn').attr("disabled", false);
					}
					$(condiv).empty();
					$(condiv).append(data);
					$('#pagenumber1').val(frenId);
					
				} // Success
			}); //$.ajax({
			}
	});

	//Get invite pop up
	$('#termsClick').live('click', function(){
		$('#overlay').show();
		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
		$('#modalCon').load('inc/terms.html');
	});
	
	//Normal Registration (might use this function when we open registration without invites
	$('#regBtn').click(function() {
		$(".rError").hide();
		
		var email = $('#regEmail').val();
		var name = $('#regUsername').val();
		var pwd = $('#regPwd').val();
		var terms = $('#terms').is(':checked');
		//alert('name: ' +name+ ', Email: ' +email+ ', Pwd: ' +pwd);
		var status = true;
		if (name == ""){
			$("#regNameError").show('blind', { direction: 'vertical' }, 300);
			$("#regNameNull").show();
			status = false;
		} else if (name.length <  6 ){
			$("#regNameError").show('blind', { direction: 'vertical' }, 300);
			$("#regNameLength").show();
			status = false;
		}
		if (email == ""){
			$("#regError").show('blind', { direction: 'vertical' }, 300);
			$("#regNull").show();
			status = false;
		} 
		if (pwd == ""){
			$("#regPwdError").show('blind', { direction: 'vertical' }, 300);
			$("#regPwdNull").show();
			status = false;
		} else if (pwd.length <  6){
			$("#regPwdError").show('blind', { direction: 'vertical' }, 300);
			$("#regPwdLength").show();	
			status = false;
		}
		
		if ((!terms) && (email != "" && name != "" && pwd != "")){
			$('#overlay').fadeIn();
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
			$('#modalCon').html("<div class='pMsg'>You've to agree the Terms & Conditions to sign up.</div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
			status = false;
		}
		if(status){
			$('#regLoading').show();
			var dataString = 'email='+ email + '&name=' + name + '&pwd=' + pwd;
	
			$.ajax({
				type: "POST",
				url: "proc/registerFinal.php",
				data: dataString,
				dataType: 'json',
				cache: false,
				success: function(data){
		
					if (data.name == 'false'){
						$("#regNameError").show('blind', { direction: 'vertical' }, 300);
						$("#regNameInvalid").show();
					} else if (data.name == 'exist') {
						$("#regNameError").show('blind', { direction: 'vertical' }, 300);
						$("#regNameExist").show();
					}
					
					if(data.reg == 'true') {
						// Email already registered
						$("#regError").show('blind', { direction: 'vertical' }, 300);
						$("#regTrue").show();
					} else if (data.reg == 'invalid') {
						// Email available for registration
						$("#regError").show('blind', { direction: 'vertical' }, 300);
						$("#regInvalid").show();
					} 
					
					$('#regLoading').hide();
					if(data.success == 'true'){
						$('#overlay').fadeIn();
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
						$('#modalCon').html("<div class='pMsg'><p>Check your email to activate your account.</p><p style='font-size: 12px; color: #cc0001;'>Please make sure to check your spam folder for the activation email.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					} else if(data.success == 'false') {
						$('#overlay').fadeIn();
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
						$('#modalCon').html("<div class='pMsg'><p>We encountered some glitches on our server. Please registering again later.</p><p>Apology for the inconvenience.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					}
				}
			});
		}// ENDS if (terms === "agree"){
	});
	
	//User Login
	$("#loginPwd").keypress(function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);
  		if ( code == 13 ) { $('#loginBtn').click();}
	});
	
	$('#loginBtn').click(function() {
		$(".errorMsg").hide();

		var email = $('#loginEmail').val();
		var pwd = $('#loginPwd').val();
		
		if($('#remember').is(':checked')) { var remember = $('#remember').val(); } else { var remember = "No"; }
	
		if (email == "" && pwd == ""){
			$("#logError").show('blind', { direction: 'vertical' }, 300);
			$("#logNullError").show();
		} else {
			$('#loginLoading').show();
			var dataString = 'email='+ email + '&pwd=' + pwd + '&rem=' + remember;
	
			$.ajax({
				type: "POST",
				url: "proc/login.php",
				data: dataString,
				dataType: 'json',
				cache: false,
				success: function(data){
					$('#loginLoading').hide();
					if (data.type == 'unverified'){
						$('#overlay').fadeIn();
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
						$('#modalCon').html("<div class='pMsg'><p>Your Email has not be verified yet.</p><p>If you did not receive a verification email from us, <a id='resendEmail' href='#'>Resend Verification Email.</a></p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					} else if (data.type == 'invalid') {
						$("#logError").show('blind', { direction: 'vertical' }, 300);
						$("#logInvalidError").show();
					} else if (data.type == 'redirect') {
						window.location = data.url; // + '?login=true';
					} 
				}
			});
		}// ENDS if (terms === "agree"){
	});
	//Hiding error message
	$('#loginEmail').blur(function(){ $(".errorMsg").hide(); });
	$('#login-pwd').blur(function(){ $(".errorMsg").hide() });
	
	//Post new story
	// Expanding text area
	$('.elastic').elastic();
	$('.oneSixty').charCount({ allowed: 160, warning: 25, counterText: '' });
	
	function submitNewStory(){
		var line = $('#sLine').val();
		var title = $('#sTitle').val();
		
		var dataString = 'line=' + encodeURIComponent(line) + '&title=' + encodeURIComponent(title);
		
		if(title.length < 1 || line.length < 1){								//If null then
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
			$('#modalCon').html("<div class='pMsg'><p>Fields can not be left blank.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
		} else if ( title.length > 160) { 					//Title can't be longer than 160 char 
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
			$('#modalCon').html("<div class='pMsg'><p>The title can not be more than 160 characters. You've typed "+title.length+" characters.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
		} else {
			$(".loadingHolder").show();
			$.ajax({
				type: "POST",
				url: "proc/newStory.php",
				data: dataString,
				cache: false,
				success: function(data){
					if(data == 'visitor') {
						var con = confirm("Do you want to signup");
						if(con){
							curUrl = document.location.href.split("?");
							document.location = curUrl[0]+'/';
						} else {
							$(".loadingHolder").hide();
						}
					} else {
						window.location = '/story/'+data;
					}
				}
			});
		}
	}
	
	$('#postNS').live('click', function(){ submitNewStory(); });
	
	//Post new Entry Line
	$("#addline").live('click', function() {
		var newline = $("#newline").val();
		var lineId = $("#lineId").val();
		var storyId = $("#storyId").val();
		
		var dataString = 'newline='+ encodeURIComponent(newline) + '&lineId=' + lineId + '&storyId=' + storyId;
		
		if(newline=='' || lineId=='' || storyId=='' || typeof newline === 'undefined' || typeof lineId === 'undefined' || typeof storyId === 'undefined') {
			// Do nothing
		} else {
			$("#loadNewLine").show();
			$.ajax({
				type: "POST",
				url: "proc/addLine.php",
				data: dataString,
				dataType : 'json',
				cache: false,
				success: function(data){
					$("#loadNewLine").hide();
					//If users posts without signing in
					if(data.type == 'visitor') {
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
						$('#modalCon').html("<div class='pMsg'><p>You need to be logged in to be able to post. Please Login first.</p></div><button class='modalClose btnGrey' style='margin-top: 10px; margin-right: 5px;'>Cancel</button><button class='btnB showIn modalClose' style='margin-top: 10px; margin-left: 5px;'>OK</button>");
					} else {
						$("#elPaneWrap").show();		
						$("ul#ntwists").prepend(data.line);
						$.scrollTo('#twists', {duration:300});
						$("ul#ntwists li:first").fadeIn("slow");
						$('ul#ntwists li:first').effect('highlight', {}, 1000);
						$("#entryForm .loadNewLine").remove();
						$("#newline").val('');
						/* sandipan- 26/08/2011--- changed to make the character left as 160*/
						$(".counter").empty();
						$(".counter").append('Characters left: 160');
					}
				}
			});
		}
		return false;
	});
	
	//Delete entry line
	$('input.del').live('click', function(){
		var btnId = $(this).attr('id');
		var lineId = $(this).data('delvalue');
		var storyId = $('#ntwists').data('id'); // Story ID (as HTML5 data-id in #ntwists)
		
		var dataString = "btnId="+btnId+"&storyId="+storyId+"&lineId="+lineId;
		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
		$('#modalCon').html("<div class='pMsg'><p>Do you really want to delete?</p></div><button class='btnGrey modalClose' style='margin: 15px 10px;'>Cancel</button><button id='delBtn' data-btnid='"+btnId+"' data-info='"+ dataString +"' class='btnO modalClose' style='margin: 15px 10px;'>OK</button>");
	});// $('input.del').live('click', function(){
	

	$('#delBtn').live('click', function(){
		var data = $(this).data('info'),
			btnId = $(this).data('btnid');
		
		$.ajax({
			type: "POST",
			url: "proc/delete.php",
			data: data,
			dataType: 'json',
			cache: false,
			success: function(data){
				if(data.type === 'true') {								//Success
					$("#new"+btnId).fadeOut(300);
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'><p>Line successfully deleted.</p></div><button class='btnB modalClose' style='margin-top:10px;'>OK</button>");
				} else if (data.type === 'false') {						//Fail
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'><p>>Unable to delete line. Please try again later.</p></div><button class='btnB modalClose' style='margin-top:10px;'>OK</button>");
				} // Success ENDS
			} 
		}); //$.ajax({
	});
	
	//Delete message 
	$('.msg-del').live('click', function(){
		var muid = $(this).data('muid');

		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
		$('#modalCon').html("<div class='pMsg'><p>Are you sure you want to delete this message?</p></div><button class='btnGrey modalClose' style='margin: 15px 10px;'>Cancel</button><button data-muid='"+muid+"' class='btnO modalClose msg-c-del' style='margin: 15px 10px;'>OK</button>");
	});// $('input.del').live('click', function(){
	
	$('.msg-c-del').live('click', function(){
		var muid = $(this).data('muid'),
			data = { "muid" : muid };

		$.getJSON( "proc/delmessage.php", data, function (json){
			if(json.status) {								//Success
				$("#msgdel"+muid).parents('li.eachLine').fadeOut(300);
				$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
				$('#modalCon').html("<div class='pMsg'><p>Message successfully deleted.</p></div><button class='btnB modalClose' style='margin-top:10px;'>OK</button>");
			} else {						//Fail
				$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
				$('#modalCon').html("<div class='pMsg'><p>Unable to delete message. Please try again later.</p></div><button class='btnB modalClose' style='margin-top:10px;'>OK</button>");
			} // Success ENDS
		});
	});
	
	
	//Reload Notification
	$('#nReload').live('click', function(){ notifications(); });

	//Voting buttons
	$('.voteUpIcon').live('click', function() {
		var count = $(this).data('count');				// Serial count		
		var uniqueid = $(this).data("uid");   				// Unique id of button clicked
		var storyId = $('#ntwists').data('id'); 			// Story ID (as HTML5 data-id in #ntwists)

		var voteUp = '#voteUp' + count;						//Getting ids for the corresponding voting buttons
		var voteDwn = '#voteDwn' + count;
		var countUp = '#countUp' + count;					//Getting ids for the corresponding vote count display
		var countDwn = '#countDwn' + count;
		
		var curVoteUp = $(voteUp).data('vote');				//Getting Current vote counts
		var curVoteDwn = $(voteDwn).data('vote');

		var dataPass = 'storyid='+storyId+'&uniqueid='+ uniqueid+'&vote=1';
		$.ajax({
			type: "POST",
			url: "proc/vote.php",
			data: dataPass,
			cache: false,
			success: function(html){
				
				if(html == 0) {
					var countedUp = +$(countUp).val() + 1;						//Incrementing vote up count
					$(voteDwn).removeClass('votedDwn');
					$(voteUp).removeClass('voteUp').addClass('votedUp');		//Changing class to show different icon
					$(countUp).val(countedUp);									//Displaying new vote value
				}
				if(html == 1) {
					var countedUp = +$(countUp).val() + 1;						//Incrementing vote Up Count
					var countedDwnRed = +$(countDwn).val() - 1;					//Decrementing vote down Count
					$(voteDwn).removeClass('votedDwn');
					$(voteUp).removeClass('voteUp').addClass('votedUp');		//Changing class to show different icon
					$(countDwn).val(countedDwnRed);
					$(countUp).val(countedUp);
				}
				if(html == 4) {
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
					$('#modalCon').html("<div class='pMsg'><p>The line you've just voted has been upgraded as the Next Twist of the story.</p></div><button class='btnB modalClose pBtn reload'>OK</button>");
				}
				if(html == 5){
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
					$('#modalCon').html("<div class='pMsg'><p>You need to logged in to be able to vote. Please Login.</p></div><button class='modalClose btnGrey' style='margin-top: 10px; margin-right: 5px;'>Cancel</button><button class='showIn btnB modalClose pBtn' style='margin-top: 10px; margin-left: 5px;'>OK</button>");
				}
			}
		});
	});
	
	$(".reload").live('click', function() { window.location.reload(); }) // Reload Page
	  
	$('.showIn').live('click', function(){
		$('#showLogin').click();
	});
	
	$('.voteDownIcon').live('click', function() {
		var count = $(this).data('count');					// Serial count		
		var uniqueid = $(this).data("uid");   				// Unique id of button clicked
		var storyId = $('#ntwists').data('id'); 			// Story ID (as HTML5 data-id in #ntwists)

		var voteUp = '#voteUp' + count;						//Getting ids for the corresponding voting buttons
		var voteDwn = '#voteDwn' + count;
		var countUp = '#countUp' + count;					//Getting ids for the corresponding vote count display
		var countDwn = '#countDwn' + count;
		
		var curVoteUp = $(voteUp).data('vote');				//Getting Current vote counts
		var curVoteDwn = $(voteDwn).data('vote');
			
		var dataPass = 'storyid='+storyId+'&uniqueid='+ uniqueid+'&vote=-1';
		$.ajax({ 
				type: "POST",
				url: "proc/vote.php",
				data: dataPass,
				cache: false,
				success: function(html){
					if(html == 0) {
						var countedDwnRed = +$(countDwn).val() + 1;					//Incrementing vote up count
						$(voteUp).removeClass('votedUp');
						$(voteDwn).removeClass('voteUp').addClass('votedUp');		//Changing class to show different icon
						$(countDwn).val(countedDwnRed);								//Displaying new vote value
					}
					if(html == 1) {	
						var countedUp = +$(countUp).val() - 1;						//Incrementing vote Up Count
						var countedDwnRed = +$(countDwn).val() + 1;					//Decrementing vote down Count
						$(voteUp).removeClass('votedUp');
						$(voteDwn).removeClass('voteDwn').addClass('votedDwn');		//Changing class to show different icon
						$(countDwn).val(countedDwnRed);
						$(countUp).val(countedUp);
					}
					if(html == 5){
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
						$('#modalCon').html("<div class='pMsg'><p>You need to logged in to be able to vote. Please Login.</p></div><button class='modalClose btnGrey' style='margin-top: 10px; margin-right: 5px;'>Cancel</button><button class='showIn btnB modalClose pBtn' style='margin-top: 10px; margin-left: 5px;'>OK</button>");
					}
				}
			});
	});
	
	//Edit Profile 
	$('#editProfile').live('click', function(){ $('#detailsPlay').hide(); $('#editDisplay').show(); });
	
	//Save new email/password
	$('#saveProfile').live('click', function(){
		$(".rError").hide();		
			
		var email  = $('#playEmail').val(),
			 pwd  = $('#playPwd').val(),
			 userId  = $('#playId').val();
		
		if(email == "" && pwd == ""){
			$("#setEmailError").show('blind', { direction: 'vertical' }, 300);
			$("#setEmailNull").show();
			
			$("#setPwdError").show('blind', { direction: 'vertical' }, 300);
			$("#setPwdNull").show();
		} else if(email == ""){
			$("#setEmailError").show('blind', { direction: 'vertical' }, 300);
			$("#setEmailNull").show();
		} else if( pwd == ""){
			$("#setPwdError").show('blind', { direction: 'vertical' }, 300);
			$("#setPwdNull").show();
		} else {
			var dataString = "email="+email+"&pwd="+pwd+"&userId="+userId;
			$.ajax({
				type: "POST",
				url: "proc/changePwd.php",
				data: dataString,
				dataType: 'json',
				cache: false,
				success: function(data){
					if (data.error == '1' || data.error == '2' ){
						$('#editDisplay').hide();
						$('#detailsPlay').fadeIn();
						$('#setEditFail').fadeIn();
						$('#setEPF').show();
					} else if (data.error == '3'){
						$('#spanEmail').html(''+email+'');
						$('#editDisplay').hide();
						$('#detailsPlay').fadeIn();
						$('#setEditSuccess').fadeIn();
						$('#setEPS').show();
					} else if (data.error == '4'){
						$("#setEmailError").show('blind', { direction: 'vertical' }, 300);
						$("#setEmailInvalid").show();
					} else if (data.error == '5'){
						$("#setEmailError").show('blind', { direction: 'vertical' }, 300);
						$("#setEmailExist").show();
					}
					$('#playPwd').val('');			//Reseting #playPwd content
				} // Success
			}); //$.ajax({ 
		}
	});
	
	//Email Subscription
	// Subscribe or Unsubscribe to email notifications
	$("#subsIp").live('click', function(){ $('#subscribeBtn').fadeIn(500); });
	
	$("#subscribeBtn").live('click', function(){
		if ($('#subsIp').is(':checked')) { var subscribe = 'true'; } else { var subscribe = 'false'; }
         var dataString = 's='+ subscribe;

		$.ajax({
			type: "POST",
			url: "proc/subscribe.php",
			data: dataString,
			dataType: 'json',
			cache: false,
			success: function(data){
				if (data.type == 'strue'){
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'>You've succesfully subscribed to email notification.</div><button class='btnB modalClose pBtn'>OK</button>");
				} else if(data.type == 'utrue'){
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'>You've succesfully unsubscribed to email notification.</div><button class='btnB modalClose pBtn'>OK</button>");
				} else if (data.type == 'false') {
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'>We encountered an error. Please try again later.</div><button class='btnB modalClose pBtn'>OK</button>");
				}				
			}
		});
	});	
	
	//Hide error displays on keypress (profile edit page)
	$('.editPlay input').keypress(function(){
		var id = $(this).attr('id');
		if (id == 'playEmail'){
			$(".eErrors").hide();
		} else if (id == 'playPwd'){
			$(".pErrors").hide();
		}
	});
	
	$('.flagIcon').live('click', function() {
		var uid = $(this).data("id");
		var count = $(this).data("count");	
		
		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
		$('#modalCon').html("<div class='pMsg'><p>Are you sure you want to Flag this post.</p><p>After receiving a certain number of flags, the post will be removed from the list.</p></div><button class='btnGrey modalClose' style='margin: 15px 10px;'>Cancel</button><button id='confirmFlag' data-count='"+count+"' data-uid='"+uid+"' class='btnB modalClose' style='margin: 15px 10px;'>OK</button></div>");
	});
	
	$('#confirmFlag').live('click', function() {
		var uniqueid = $(this).data("uid");   // Getting unique ID of the entryline
		var storyId = $('#ntwists').data('id'); // Story ID 
		var count = $(this).data("count");
	
		var dataPass = 'storyid='+storyId+'&uniqueid='+ uniqueid+'&flag=1';
		$.ajax({
			type: "POST",
			url: "proc/flag.php",
			data: dataPass,
			cache: false,
			success: function(html){
				// Show error if error is there
				if(html == 1) {
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
					$('#modalCon').html("<div><div class='s-msg'><p>The post has been flagged successfully.</p></div><button class='btnB modalClose' style='margin: 15px 10px;'>OK</button></div>");
				}
				if(html == 2) {
					//Flag limit reached. The line will've been removed on next relaod
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
					$('#modalCon').html("<div><div class='s-msg'><p>The post has been flagged successfully.</p></div><button class='btnB modalClose' style='margin: 15px 10px;'>OK</button></div>");
				}
				if(html == 3) {
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
					$('#modalCon').html("<div><div class='s-msg'><p>You have already flagged the line.</p></div><button class='btnB modalClose' style='margin: 15px 10px;'>OK</button></div>");
				}
			}
		});
	});
	
	//FB share
	$('.fbShareIcon').live('click', function(){
		var line = $(this).data('line');
		var eline = decodeURIComponent($(this).data('eline'));
		var uid = $(this).data('uid');
		var stryid = $(this).data('stryid');
		callFB(line, eline, stryid, uid);
	})
	
	//Following user
	$('#connect').live('click', function(){
		var frenId = $('#connect').val();
		$('#connect').attr('disabled', 'disabled');		
		var dataString = "frenId="+frenId;
		$.ajax({
			type: "POST",
			url: "proc/frenrequest.php",
			data: dataString,
			dataType: 'json',
			cache: false,
			success: function(data){
				if (data.type == 'false'){
					$('#connect').fadeOut(200);
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'><p>You are now following this user. The user has been notified.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					$('#dConnect').fadeIn(100);
				} else if (data.type == 'true') {
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'><p>Failed to follow the user. Please try again later.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
				}					
			} // Success
		}); //$.ajax({ 
	});
	
	//Following user from Invite page
	$('.email-follow-btn').live('click', function(){
		var frenId = $(this).data('fid');
		var dataString = "frenId="+frenId,
			elem = $(this);
		
		$.ajax({
			type: "POST",
			url: "proc/frenrequest.php",
			data: dataString,
			dataType: 'json',
			cache: false,
			success: function(data){
				if (data.type == 'false'){
					elem.removeClass('btnLb email-follow-btn').addClass('btnG');
					elem.html('Following');
				} else if (data.type == 'true') {
					elem.removeClass('btnLb email-follow-btn').addClass('btnR');
					elem.html('Failed');
				}
			} // Success
		}); //$.ajax({ 
	});
	
	$('#dConnect').live('click', function(){
		var frenId = $('#dConnect').data('frenid');
		var myid = $('#dConnect').data('myid');
		
		var dataString = "frenId="+frenId+"&myid="+myid;
		$.ajax({
			type: "POST",
			url: "proc/unfollow.php",
			data: dataString,
			dataType: 'json',
			cache: false,
			success: function(data){
				if (data.type == 'true'){
					$('#dConnect').hide();
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'><p>You are no longer following this user.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					$('#connect').show();
				} else if (data.type == 'false') {
					$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
					$('#modalCon').html("<div class='pMsg'><p>Failed to unfollow the user. Please try again later.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
				}					
			} // Success
		}); //$.ajax({ 
	});
	
	// Feedback
	$('#fBack').live('click', function(){
		$('#overlay').show();
		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
		$('#modalCon').load( 'inc/feedback.php');
	});
	
	$('#s-feedback').live('click', function() {
		$('.fror').hide();
		var name = $('#f-name').val();
		var email = $('#f-email').val();
		var msg = $('#f-message').val();

		if(name== "" || email == "" || msg == ""){
			$("#f-error-2").show('blind', { direction: 'vertical' }, 300);
		}else {
			$('#a-loading').show();
			var dataString = 'name='+ name + '&email=' + email + '&msg=' + msg;
			$.ajax({
				type: "POST",
				url: "proc/sendFback.php",
				data: dataString,
				dataType: 'json',
				cache: false,
				success: function(data){
					$('#a-loading').hide();		
					if (data.type == 'true'){
						$('#modalWrap').hide();
						$('#modalWrap').fadeIn();
						$('#modalCon').html("<div id='pop-s-msg'><div class='s-msg'><p>Your feedback has been submitted succesfully.</p></div><button class='btnB modalClose' style='margin-top: 15px;'>OK</button></div>");
					} else if (data.type == 'false') {
						$("#f-error-1").show('blind', { direction: 'vertical' }, 300);
					} 
				}
			});
		}

	});
	
	
	
	//Remove Photo
	$('#rmvBtn').live('click', function(){ 
		var id = $(this).data('uid');
		$('#dpOverlay').show();
		var dataString = "userId="+id;
			$.ajax({
				type: "POST",
				url: "proc/deletePhoto.php",
				data: dataString,
				dataType: 'json',
				cache: false,
				success: function(data){
					if (data.type == 1 ){
						//Successfully deleted
						$('#dPic').attr({src: data.src});
						$('.avatar').attr({src: data.src});
						$('#dpOverlay').hide();
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
						$('#modalCon').html("<div class='pMsg'>Display Picture removed successfully</div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");						
					} else if (data.type == 2){
						//User Doesn't exist
						$('#dpOverlay').hide();
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
						$('#modalCon').html("<div class='pMsg'>Display Picture could not removed<p>User does not exist.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					} else if (data.type == 3){
						//un authorized attempt
						$('#dpOverlay').hide();
						$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
						$('#modalCon').html("<div class='pMsg'>Display Picture could not removed<p>You are not authorised to remove the profile image.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
					} 
				} // Success
			}); //$.ajax({ 
	});
	
	//Upload photo
	//Show upload/remove pop up
	$('#dpUploadBtn').live('click', function(){
		var id = $(this).data('uid');
		$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
		$('#modalCon').load("inc/avatarUpload.php");
	});
	
	// on clicking change photo show loading image
	$('#profilePhoto').live('change', function(){
		$('#modalWrap').fadeOut(300);
		$('#fileUploadForm').submit();
		$('#dpOverlay').show();
		//hide popup
		$('#chng_prfl_pht_link').removeClass("hide");
		$('#chng_prfl_pht_popup').addClass("hide");
	});

	//Confirm facebook account merge with email account
	$('#fbConfirm').live('click', function() {
		FB.api('/me', function(response) {
			var data = {
				'id' : response.id,
				'email' : response.email,
				'fname' : response.first_name,
				'lname' : response.last_name
			}

			$.getJSON( "proc/fbmerge.php", data, function (json){
				if(json.status){ 
					window.location = "/";
				}
			});
		});
	});
	
	//If user hasn't set facebook username, register user by taking in username from pop-up
	$('#fbLoginNow').live('click', function() {
		var uname = $('#regFbUsername').val(),
			error = true,
			ck_username = /^[A-Za-z0-9_\.-]{5,20}$/;
		
		if(uname == ''){
			//Do nothing
			$(".errorMsg").hide();
			error = false;
		} else if (!ck_username.test(uname)){
			$(".errorMsg").hide();
			$("#regErrorWrap").show('blind', { direction: 'vertical' }, 300);
			$("#usernameChar").show();
			error = false;
		}

		if(error){
			FB.api('/me', function(response) {
				var data = {
					'id' : response.id,
					'email' : response.email,
					'fname' : response.first_name,
					'lname' : response.last_name,
					'username' : uname,
					'type' : 'skip'
				}

				$.getJSON("proc/fblogin.php", data, function (json){
					if(json.status == 'register'){
						window.location = "/";
					} else if (json.status == 'unavailable'){
						$(".errorMsg").hide();
						$("#regErrorWrap").show('blind', { direction: 'vertical' }, 300);
						$("#usernameAvailability").show();
					}
				});
			});
		}
	});
	
	//Tour starts
	
		//Show New story post field
		$('#startTour').live('click', function(){
			$('#splash-info').hide();
			$('#overlay').show();
			$('#content').show();
			$('#newStory').css({
				"position": "relative",
				"z-index": 100
			});
			$('#tour-start').show();
		});
		
		//Show story lines & add line post field
		$('#tour-story').live('click', function(){
			$('#newStory').css({
				"position": "relative",
				"z-index": 0
			});
			$('#tour-start').hide();
			$('.story').css({
				"position": "relative",
				"z-index": 100,
				"background-color": "#FFF",
				"padding": "20px 0"
			});
			$('#tour-storyline').fadeIn();
		});
		
		//Show entry lines
		$('#tour-entry').live('click', function(){
			$('#tour-storyline').hide();
			
			$('#reveal-meta').show();
			$('#reveal-meta .showElines').click();
			$('#tour-showTwists').fadeIn();
			$('#tour-showTwists-img').fadeIn();
		});
		
		//Last from twists
		$('#tour-twists').live('click', function(){
			$('.story').css({
				"padding": "0",
				"z-index": 0
			});
			$('#tour-storyline').hide();
			$('#tour-showTwists').hide();
			$('#tour-showTwists-img').hide();
			$('#twists').css({
				"position": "relative",
				"z-index": 100,
				"padding": "20px 0"
			});
			$.scrollTo('#ntwists', 300);
			$('#tour-entryline').fadeIn();
		});
		
		$('#tour-end').live('click', function(){
			window.location = "index.php?page=hot";
		});

	$('#profilePhoto').live({
		mouseenter: function(){ $('#changeBtn').trigger("mouseover"); },
        mouseleave: function(){ $('#changeBtn').trigger("mouseout"); }
     });
	 
	 $(".strLine").live("mouseover mouseout", function(event) {
		if (event.type == "mouseover" ) {
			$(this).find('.lineMtaItemOne').show();
		} else {
			$(this).find('.lineMtaItemOne').hide();
		}
	});
	
	$('.showElines').live('click', function(){
		//If already not visible show it
		if(!$(this).parents('.eachLine').children('.viewEntryLines').is(":visible")){
			$(this).parents('.eachLine').children('.viewEntryLines').show('blind', { direction: 'vertical' }, 300);
		}
	});
	
	$('.eTwistsClose').live('click', function(){
		//If already not visible show it
		if($(this).parents('.eachLine').children('.viewEntryLines').is(":visible")){
			$(this).parents('.eachLine').children('.viewEntryLines').hide('blind', { direction: 'vertical' }, 300);
		}
	});
	
	//Invite through Gmail contants
	$('.email-invite-btn').live('click', function(){
		//If already not visible show it
		var email = $(this).data('email'),
			data = { "email" : email },
			elem = $(this);
			//sendEmailInvite(elem, data);
			$.getJSON( "proc/sendinvite.php", data, function (json){
				if(json.status){ 
					//Invite successfully sent
					elem.removeClass('btnB email-invite-btn').addClass('btnG');
					elem.html('Invited');
				} else{
					//Invite failed
					elem.removeClass('btnB email-invite-btn').addClass('btnR');
					elem.html('Failed');
				}
			});
	});
	
	//Invite using email field
	$('#email-invite').live('click', function(){
		//If already not visible show it
		var email = $('#invite-email-field').val(),
			data = { "email" : email },
			elem = $(this);
		
		var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i 

		if(!ck_email.test(email)){
			$("#invite-email-error").show('blind', { direction: 'vertical' }, 300);
			$("#i-e-invalid").show();
		} else {
			//sendEmailInvite(elem, data);
			$.getJSON( "proc/sendinvite.php", data, function (json){
				if(json.status){ 
					//Invite successfully sent
					$("#invite-email-error").show('blind', { direction: 'vertical' }, 300);
					$("#i-e-success").show();
				} else{
					//Invite failed
					$("#invite-email-error").show('blind', { direction: 'vertical' }, 300);
					$("#i-e-fail").show();
				}
			});
		}
	});
	
	//Hide Invite error
	$('#invite-email-field').live('keypress', function(){
		$("#invite-email-error").hide('blind', { direction: 'vertical' }, 300);
		$(".rError").hide();
	});
	
	//Twitter sign in
		$('#ttr-merge').live('click', function(){
			$("#new-account-div").hide();
			$('#ttr-merge-form').show();
			$("#merge-div").show('blind', { direction: 'vertical' }, 300);
		});
		
		$('#ttr-new').live('click', function(){
			$("#merge-div").hide();
			$('#ttr-merge-form').show();
			$("#new-account-div").show('blind', { direction: 'vertical' }, 300);
		});
	
	//Send message
	
		$('.msg-new').live('click', function(){
			var id = $(this).data('id');
			
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
			if(id == 'custom'){
				$('#modalCon').load('inc/msgForm.php?to=custom');
			} else {
				$('#modalCon').load('inc/msgForm.php?to='+id);
			}
		});
		
		
		$('#msg-send').live('click', function(){
			$('#msg-form .loader').show();
			var to = $(this).data('to'),
				msg = $('#msg-content').val(),
				data = {
						"to" : to,
						"msg" : msg
					};
			
			if(msg.length > 500){
				$('#msg-form .loader').hide();
				$('#msg-form .errorMsg').show();
			} else {
				$.getJSON( "proc/sendmessage.php", data, function (json){
					$('#msg-form .loader').hide();
					if(json.status){ 
						//Invite successfully sent
						$('#modalCon').html("<div class='pMsg'><p style='margin-bottom: 15px'>Your message has been sent successfully.</p><p><a href='index.php?page=message&id="+json.msgid+"'>View Message</a></p><button id='okBtn' class='btnB modalClose pBtn' style='margin-bottom: 20px'>OK</button>");
					} else{
						//Invite failed
						$('#modalCon').html("<div class='pMsg'><p>Unable to send message. Please try again later.</p><button id='okBtn' class='btnB modalClose pBtn' style='margin-bottom: 20px'>OK</button>");
					}
				});
			}
		});
		
		//Check message length
		$("#msg-content").live('keypress', function() {
			var msg = $('#msg-content').val();
			
			if(msg.length > 500){
				$('#msg-form .errorMsg').show();
				$('#sendMsgFrm .errorMsg').show();
			} else {
				$('#msg-form .errorMsg').hide();
				$('#sendMsgFrm .errorMsg').hide();
			}
		});
		
		
		$('#msg-sendid').live('click', function(){
			$('#sendMsgFrm .loader').show();
			var msgid = $(this).data('msgid'),
				msg = $('#msg-content').val(),
				data = {
						"msgid" : msgid,
						"msg" : msg
					};
			if(msg.length > 500){
				$('#sendMsgFrm .loader').hide();
				$('#sendMsgFrm .errorMsg').show();
			} else {
				$.getJSON( "proc/sendmessage.php", data, function (json){
					$('#sendMsgFrm .loader').hide();
					if(json.status){ 
						//Invite successfully sent
						$('.msg-list').append(json.markup);
						$('#msg-content').val('');
					} else{
						//Invite failed
						$('.msg-list').append("<li class='eachLine box' style='border-top: 1px solid #CCC;'>Unable to send message. Please try again later.</li>");
					}
				});
			}
		});

	
	document.getElementById("fileUploadForm").onsubmit=function()	{
		document.getElementById("uploadTarget").onload = uploadDone(); 
		//This function should be called when the iframe has compleated loading
		// That will happen when the file is completely uploaded and the server has returned the data we need.
	}
});


function uploadDone() { //Function will be called when iframe is loaded
	var ret = frames['uploadTarget'].document.getElementsByTagName("body")[0].innerHTML;
	var data = eval("("+ret+")"); //Parse JSON 
	str = data.file_name;
	  
	if(data.failure!='invalid') {
		if(str){ //on success
			$('#dPic').attr({src: str});					//Changing source URL for profile display
			$('.avatar').attr({src: data.avatar_icon});
			$('#dPic').attr({src: str});
			$('#dpOverlay').hide();
			// show success message
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
			$('#modalCon').html("<div class='pMsg'>Your profile photo has been changed successfully.</div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
		}  else  { //on failure
			// show error message
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
			$('#modalCon').html("<div class='pMsg'>Sorry, we were not able to upload your photo. Please try again later.</div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
			$('#dpOverlay').hide();
		}
	} else {
			// Invalid photo 
			$('#modalWrap').show('clip', { direction: 'horizontal' }, 100)
			$('#modalCon').html("<div class='pMsg'>It seems the photo you are uploading is invalid. Please try uploading a gif, jpeg or png photo.</div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
	}
}

function temp(){
	$('#modalWrap').show('clip', { direction: 'horizontal' }, 100);
	$('#modalCon').html("<div class='pMsg'><p>Fields can not be left blank.</p></div><button id='okBtn' class='btnB modalClose pBtn'>OK</button>");
}